package com.lb.uts.web;

import com.lb.uts.constants.UTSConstants;
import com.lb.uts.exception.UTSException;
import com.lb.uts.constants.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * uts controller的基础父类</p>
 * 提供全局的异常捕获:</p>
 *
 * @author liangb
 * @version 3.0
 * @date 2019/4/26 15:03
 * @see #exception(Exception, HttpServletRequest) </p>
 * 提供全局方法:</p>
 * @see #wrapErrResp(Class, String)
 * @see #wrapSuccessResp(Class)
 */
@Controller
public class UtsBaseController {

    private static final Logger logger = LoggerFactory.getLogger(UtsBaseController.class);

    /**
     * 封装输入参数校验错误返回结果
     *
     * @param clazz {@link BaseResponse}的子类
     * @param msg   需要提示的消息
     * @param <T>   {@link BaseResponse}的子类
     * @return {@link BaseResponse}的实例或者null
     */
    protected static <T extends BaseResponse> T wrapErrResp(Class<T> clazz, String msg) {
        T t = null;
        try {
            t = clazz.newInstance();
            t.setReturnCode(UTSConstants.FAIL_CODE);
            t.setReturnMsg(msg);
        } catch (InstantiationException e) {
        } catch (IllegalAccessException e) {
        }
        return t;
    }

    /**
     * 封装正确返回结果
     *
     * @param clazz {@link BaseResponse}的子类
     * @param <T>   {@link BaseResponse}的子类
     * @return {@link BaseResponse}的实例或者null
     */
    protected static <T extends BaseResponse> T wrapSuccessResp(Class<T> clazz) {
        T t = null;
        try {
            t = clazz.newInstance();
            t.setReturnCode(UTSConstants.SUCCESS_CODE);
        } catch (InstantiationException e) {
        } catch (IllegalAccessException e) {
        }
        return t;
    }


    /**
     * 统一异常处理
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler
    @ResponseBody
    public Map<String, String> exception(Exception e, HttpServletRequest request) {
        Map<String, String> returnMap = new HashMap<>();
        if (e instanceof UTSException) {
            UTSException utsException = (UTSException) e;
            logger.info("定时任务系统---------------->" + utsException.toString());
            returnMap.put("returnCode", utsException.getErrorCode());
            returnMap.put("returnMsg", utsException.getErrorMsg());
            return returnMap;
        } else {
            logger.error("定时任务系统---------------->系统异常"+e);
            returnMap.put("returnCode", "9999");
            returnMap.put("returnMsg", "系统异常请稍后重试");
            return returnMap;
        }
    }

}
